package com.km.wskj.itmonitor.pager.monitor.server;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.server.domain.History;
import com.km.wskj.itmonitor.pager.monitor.server.domain.Rats;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.os.Build.VERSION_CODES.M;


//服务器历史性能页面
public class ServerHistoryActivity extends LActivity {
    private static final String TAG = "ServerHistoryActivity";

    private final static int CPU_INDEX = 1;
    private final static int MEMORY_INDEX = 2;
    private final static int NET_INDEX = 3;

    //ui
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.lineChart_cpu)
    LineChart lineChartCpu;
    @BindView(R.id.lineChart_memory)
    LineChart lineChartMemory;
    @BindView(R.id.lineChart_internet)
    LineChart lineChartInternet;

    private String id;
    private String ip;

    String begTime = "2017-05-1 00:00:00";
    String endTime = "2017-05-1 06:00:00";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_history);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("id"))
            id = getIntent().getStringExtra("id");
        if (getIntent().hasExtra("ip"))
            ip = getIntent().getStringExtra("ip");
        toolBarTitle.setText(ip != null ? ip : "");
        toolBarBack.setVisibility(View.VISIBLE);

        initData();
    }

    private void initData() {
        //cpu
        pdc.historyCpu(HTTP_TASK_TAG, id, begTime, endTime, new ZxlGenericsCallback<History>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(History history, int i) {
                initChart(lineChartCpu, CPU_INDEX, history.times.size(), history.rats);
            }
        });

        //内存
        pdc.historyMemory(HTTP_TASK_TAG, id, begTime, endTime, new ZxlGenericsCallback<History>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(History history, int i) {
                initChart(lineChartMemory, MEMORY_INDEX, history.times.size(), history.rats);
            }
        });

        //网络
        pdc.historyInternet(HTTP_TASK_TAG, id, begTime, endTime, new ZxlGenericsCallback<History>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(History history, int i) {

            }
        });
    }


    /**
     * @param mChart
     * @param type
     * @param count  //初始化折线图方法
     */
    private void initChart(LineChart mChart, int type, int count, List<Rats> data) {
        // no description text
        mChart.getDescription().setEnabled(false);
        // enable touch gestures
        mChart.setTouchEnabled(true);
        mChart.setDragDecelerationFrictionCoef(0.9f);
        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(true);
        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);
        // set an alternative background color
        mChart.setBackgroundColor(Color.WHITE);

        // add data
        // 根据不同的类型调用不同的设置数据方法
        switch (type) {
            //cpu历史性能
            case CPU_INDEX:
                setCpuData(count, data, mChart);
                break;
            //内存
            case MEMORY_INDEX:
                setMemoryData(count, data, mChart);
                break;
            //网络
            case NET_INDEX:

                break;
        }

//        setCpuData(20, 30, mChart);

        mChart.animateX(2500);
        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();
        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        l.setTextSize(11f);
        l.setTextColor(getResources().getColor(R.color.text_gray));
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
//        l.setYOffset(11f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setTextSize(11f);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.enableGridDashedLine(10f, 10f, 0f); //设置网格线为虚线效果
        leftAxis.setDrawZeroLine(false); //是否绘制0所在的网格线
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);//不要右边
    }

    //设置cpu数据
    private void setCpuData(int count, List<Rats> mData, LineChart mChart) {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();//User
        ArrayList<Entry> yVals2 = new ArrayList<Entry>();//Total
        ArrayList<Entry> yVals3 = new ArrayList<Entry>();//Sys
        //添加数据
        for (int i = 0; i < count; i++) {
            Rats rats = mData.get(i);
            yVals1.add(new Entry(i, rats.User));//添加user的数据
            yVals2.add(new Entry(i, rats.Total));//添加Total的数据
            yVals3.add(new Entry(i, rats.Sys));//添加Sys的数据
        }

        LineDataSet set1, set2, set3;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);
            set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);

            set1.setValues(yVals1);
            set2.setValues(yVals2);
            set3.setValues(yVals3);

            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();

        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "User");
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setCircleColor(Color.WHITE);
            set1.setLineWidth(1f);
            set1.setCircleRadius(0f);
            set1.setFillAlpha(65);
            set1.setFillColor(ColorTemplate.getHoloBlue());
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);
            set1.setDrawValues(false);// 不显示坐标点的数据
            set1.setDrawCircles(false);//// 不显示坐标点的小圆点
            //set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            // create a dataset and give it a type
            set2 = new LineDataSet(yVals2, "Total");
            set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set2.setColor(Color.RED);
            set2.setCircleColor(Color.WHITE);
            set2.setLineWidth(1f);
            set2.setCircleRadius(0f);
            set2.setFillAlpha(65);
            set2.setFillColor(Color.RED);
            set2.setDrawCircleHole(false);
            set2.setHighLightColor(Color.rgb(244, 117, 117));
            set2.setDrawValues(false);// 不显示坐标点的数据
            set2.setDrawCircles(false);//// 不显示坐标点的小圆点
            //set2.setFillFormatter(new MyFillFormatter(900f));

            set3 = new LineDataSet(yVals3, "Sys");
            set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set3.setColor(Color.YELLOW);
            set3.setCircleColor(Color.WHITE);
            set3.setLineWidth(1f);
            set3.setCircleRadius(0f);
            set3.setFillAlpha(65);
            set3.setFillColor(ColorTemplate.colorWithAlpha(Color.YELLOW, 200));
            set3.setDrawCircleHole(false);
            set3.setHighLightColor(Color.rgb(244, 117, 117));
            set3.setDrawValues(false);// 不显示坐标点的数据
            set3.setDrawCircles(false);//// 不显示坐标点的小圆点


            // create a data object with the datasets
            LineData data = new LineData(set1, set2, set3);
            data.setValueTextColor(Color.WHITE);
            data.setValueTextSize(9f);

            // set data
            mChart.setData(data);
        }
    }


    //设置内存数据
    private void setMemoryData(int count, List<Rats> mData, LineChart mChart) {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();//physicsMem
        ArrayList<Entry> yVals2 = new ArrayList<Entry>();//freePhysicsMem
        ArrayList<Entry> yVals3 = new ArrayList<Entry>();//freeVirtualMem
        ArrayList<Entry> yVals4 = new ArrayList<Entry>();//virtualMem

        //添加数据
        for (int i = 0; i < count; i++) {
            Rats rats = mData.get(i);
            yVals1.add(new Entry(i, rats.physicsMem));//添加physicsMem的数据
            yVals2.add(new Entry(i, rats.freePhysicsMem));//添加freePhysicsMem的数据
            yVals3.add(new Entry(i, rats.freeVirtualMem));//添加freeVirtualMem的数据
            yVals4.add(new Entry(i, rats.virtualMem));//添加virtualMem的数据
        }

        LineDataSet set1, set2, set3, set4;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);
            set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);
            set4 = (LineDataSet) mChart.getData().getDataSetByIndex(3);

            set1.setValues(yVals1);
            set2.setValues(yVals2);
            set3.setValues(yVals3);
            set4.setValues(yVals4);

            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();

        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "physicsMem");
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setCircleColor(Color.WHITE);
            set1.setLineWidth(1f);
            set1.setCircleRadius(0f);
            set1.setFillAlpha(65);
            set1.setFillColor(Color.BLUE);
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);
            set1.setDrawValues(false);// 不显示坐标点的数据
            set1.setDrawCircles(false);//// 不显示坐标点的小圆点
            //set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            // create a dataset and give it a type
            set2 = new LineDataSet(yVals2, "freePhysicsMem");
            set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set2.setColor(Color.RED);
            set2.setCircleColor(Color.WHITE);
            set2.setLineWidth(1f);
            set2.setCircleRadius(0f);
            set2.setFillAlpha(65);
            set2.setFillColor(Color.RED);
            set2.setDrawCircleHole(false);
            set2.setHighLightColor(Color.rgb(244, 117, 117));
            set2.setDrawValues(false);// 不显示坐标点的数据
            set2.setDrawCircles(false);//// 不显示坐标点的小圆点
            //set2.setFillFormatter(new MyFillFormatter(900f));

            set3 = new LineDataSet(yVals3, "freeVirtualMem");
            set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set3.setColor(Color.YELLOW);
            set3.setCircleColor(Color.WHITE);
            set3.setLineWidth(1f);
            set3.setCircleRadius(0f);
            set3.setFillAlpha(65);
            set3.setFillColor(Color.YELLOW);
            set3.setDrawCircleHole(false);
            set3.setHighLightColor(Color.rgb(244, 117, 117));
            set3.setDrawValues(false);// 不显示坐标点的数据
            set3.setDrawCircles(false);//// 不显示坐标点的小圆点

            set4 = new LineDataSet(yVals3, "virtualMem");
            set4.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set4.setColor(Color.GREEN);
            set4.setCircleColor(Color.WHITE);
            set4.setLineWidth(1f);
            set4.setCircleRadius(0f);
            set4.setFillAlpha(65);
            set4.setFillColor(Color.GREEN);
            set4.setDrawCircleHole(false);
            set4.setHighLightColor(Color.rgb(244, 117, 117));
            set4.setDrawValues(false);// 不显示坐标点的数据
            set4.setDrawCircles(false);//// 不显示坐标点的小圆点


            // create a data object with the datasets
            LineData data = new LineData(set1, set2, set3, set4);
            data.setValueTextColor(Color.WHITE);
            data.setValueTextSize(9f);

            // set data
            mChart.setData(data);
        }
    }


    @OnClick(R.id.tool_bar_back)
    public void onClick() {
        finish();
    }

}
